<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormRules, ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
// 导入加密模块
import { encrypt }  from '../../../util/encryption'

// 导入登录保存的存储函数
import useLoginStore from '@/stores/login/login'

import type { LoginAccount } from '../../../types'
import { localCache } from '@/util/cache.ts'

// 定义account的数据
const account = reactive<LoginAccount>({
	username: localCache.getCache('username') ?? "", // 缓存里面有用户就填入，没有用户就为空
	password: localCache.getCache('password') ?? "",  // 缓存里面有密码就填入，没有密码就为空
})

// 校验规则
const accountRules: FormRules = {
	username: [
    { required: true, message: '请输入帐号', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{3,16}$/, message: '长度必须为3~16个字母和数字组成', trigger: 'blur' },
  ],
  	password: [
  	{ required: true, message: '请输入密码', trigger: 'blur' },
  	{ pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\W_])(.{8,20})$/, message: '长度必须为8以上的大小字母、特殊字符和数字组成', trigger: 'blur' }
  	]
}

// 执行账号的登录逻辑
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
function loginAction(isRemPwd: boolean) {
    formRef.value?.validate((valid) => {
        if (valid) {
            // 获取用户输入的帐号和密码
            const username = account.username
            // const password = encrypt(account.password)  //  个输入的密码加密
            const password = account.password

            // 存储登录信息
            loginStore.loginAccountAction({username, password}).then(() => {
              // 判断isRemPwd 为true 则记住密码
              if (isRemPwd) {
                localCache.setCache("username",username)
                localCache.setCache("password",password)
              }else {
                localCache.removeCache("username")
                localCache.removeCache("password")
              }
            })
            // 向服务器发送网络请求
        }else {
            ElMessage.error('输入的用户名或密码的规则不正确')
        }
    })
}
defineExpose({
    loginAction    // 将方法暴露出去
})


</script>


<template>
    <div class="pane-account">
        <el-form :model="account" :rules="accountRules" label-width="60px" size="large" status-icon ref="formRef">
            <el-form-item label="帐号" prop="username">
                <el-input v-model="account.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="account.password" show-password />
            </el-form-item>
        </el-form>
    </div>
</template>


<style scoped>

</style>


